//
//  TranslationViewController.m
//  Community-for-college
//
//  Created by NewBee_Liang on 2016/11/14.
//  Copyright © 2016年 彭鑫. All rights reserved.
//
// 发送
#define SENDER_ANIMATION_IMAGEVIEW_IMAGE_DEFAULT @"chat_sender_audio_playing_full" // 小喇叭默认图片
#define SENDER_ANIMATION_IMAGEVIEW_IMAGE_01 @"chat_sender_audio_playing_000" // 小喇叭动画第一帧
#define SENDER_ANIMATION_IMAGEVIEW_IMAGE_02 @"chat_sender_audio_playing_001" // 小喇叭动画第二帧
#define SENDER_ANIMATION_IMAGEVIEW_IMAGE_03 @"chat_sender_audio_playing_002" // 小喇叭动画第三帧
#define SENDER_ANIMATION_IMAGEVIEW_IMAGE_04 @"chat_sender_audio_playing_003" // 小喇叭动画第四帧

// 接收
#define RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_DEFAULT @"chat_receiver_audio_playing_full" // 小喇叭默认图片
#define RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_01 @"chat_receiver_audio_playing000" // 小喇叭动画第一帧
#define RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_02 @"chat_receiver_audio_playing001" // 小喇叭动画第二帧
#define RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_03 @"chat_receiver_audio_playing002" // 小喇叭动画第三帧
#define RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_04 @"chat_receiver_audio_playing003" // 小喇叭动画第四帧
#define CC_MD5_DIGEST_LENGTH    16          /* digest length in bytes */


#import "TranslationViewController.h"
#import "TranslateToolCell.h"
#import "YMReplyInputView.h"//键盘
#import <AVFoundation/AVFoundation.h>
#import <CommonCrypto/CommonDigest.h>
#import "ToolView.h"
// 讯飞语音
#import "iflyMSC/IFlyMSC.h"
#import "IATConfig.h"
#import "HWHttpTool.h"
#import "TranslateModel.h"
#import <SVProgressHUD/SVProgressHUD.h>
#import "LanguageTBV.h"//选择语言的页面
#import "NewsViewController.h"//跳转回首页新闻页面
@interface TranslationViewController ()<AVSpeechSynthesizerDelegate,IFlyRecognizerViewDelegate,IFlyPcmRecorderDelegate,IFlySpeechRecognizerDelegate,InputDelegate,UITableViewDelegate,UITableViewDataSource>
{
    
    AVSpeechSynthesizer *speechPlayer;//播放翻译语音
    AVSpeechUtterance *utterance;
    NSString *fromWhere;
    TranslateToolCell *didSelect;//不同cell的选择
    IFlyRecognizerView *_iflyRecognizerView; // 讯飞语音识别
    
}

@property (weak, nonatomic) IBOutlet UIView *ButtonView;
//承接控件的view
@property (nonatomic,strong)ToolView *toolView;

//聊天table
@property (weak, nonatomic) IBOutlet UITableView *messageTable;

//左侧的键盘
@property (weak, nonatomic) IBOutlet UIButton *Redkeyboard;
//左侧的麦克
@property (weak, nonatomic) IBOutlet UIButton *RedVoice;
//左侧国家国旗
@property (weak, nonatomic) IBOutlet UIButton *RedCountry;
//左侧语言种类
@property (weak, nonatomic) IBOutlet UILabel *RedLanguage;

//交换语言种类按钮
@property (weak, nonatomic) IBOutlet UIButton *ChangeButton;

//右侧键盘
@property (weak, nonatomic) IBOutlet UIButton *BluKeyboard;
//右侧麦克
@property (weak, nonatomic) IBOutlet UIButton *BluVoice;
//右侧国家国旗
@property (weak, nonatomic) IBOutlet UIButton *BluCountry;
//右侧语言种类显示
@property (weak, nonatomic) IBOutlet UILabel *BluLanguage;
@property (weak, nonatomic) IBOutlet UIButton *redTapBtn;
@property (weak, nonatomic) IBOutlet UIButton *blueTapBtn;

//语音功能
@property (strong, nonatomic)   AVAudioRecorder  *recorder;//录音器
@property (strong, nonatomic)   AVAudioPlayer    *player;//播放器
@property (strong, nonatomic)   NSString         *recordFileName;
@property (strong, nonatomic)   NSString         *recordFilePath;

@property (strong, nonatomic)   NSMutableArray *textMuArr;


@property (nonatomic,strong) NSString *string;
@property (nonatomic,strong) NSString *str;
@property (nonatomic,strong) NSString *text;

//翻译
@property (nonatomic,copy)NSString *fromLancode;//翻译原语种
@property (nonatomic,copy)NSString *toLancode;//翻译后的语种


@property (nonatomic,strong) IFlyPcmRecorder *pcmRecorder;//录音器，用于音频流识别的数据传入

@property (nonatomic, strong) YMReplyInputView *replyView;

@end

@implementation TranslationViewController

- (void)setValue:(id)value forUndefinedKey:(NSString *)key
{
    
}

-(void)viewWillAppear:(BOOL)animated{
    NSString *redLanCode = [UserDefaults objectForKey:kredTranslationLanCode];
    if (redLanCode.length>0) {
        _fromLancode = redLanCode;
        _RedLanguage.text = [UserDefaults objectForKey:kredTranslationLanName];
    }else{
        _fromLancode = @"zh";
        _RedLanguage.text  = @"中文";
        [UserDefaults setObject:@"zh" forKey:kredTranslationLanCode];
        [UserDefaults setObject:@"中文" forKey:kredTranslationLanName];
    }
    
    NSString *toLanStr = [UserDefaults objectForKey:@"transBaiduCode"];
    NSString *blueLanCode = [UserDefaults objectForKey:kblueTranslationLanCode];
    if (blueLanCode.length>0) {
        _toLancode = blueLanCode;
        _BluLanguage.text = [UserDefaults objectForKey:kblueTranslationLanName];
    }else if(toLanStr.length>0&&![[UserDefaults objectForKey:@"transLanguageName"] isEqualToString:@"<null>"]){
        _toLancode = toLanStr;
        _BluLanguage.text =[UserDefaults objectForKey:@"transLanguageName"];
    }else{
        _toLancode = @"en";
        _BluLanguage.text  = @"English";
        [UserDefaults setObject:@"en" forKey:kblueTranslationLanCode];
        [UserDefaults setObject:@"English" forKey:kblueTranslationLanName];
    }
    
    // 初始化识别对象
    [self initRecognizer];
    // 初始化语音识别控件
    [self initiFlyReconizerView];
    
    
}

////设置返回按钮
//-(void)setupBarButtonItem
//{
//    UIButton* left = [UIButton buttonWithType:UIButtonTypeCustom];
//    left.frame = CGRectMake(0, 0, 40, 40);
//    
//    [left setImage:[UIImage imageNamed:@"返回"] forState:(UIControlStateNormal)];
//    [left addTarget:self action:@selector(navLeftAction:) forControlEvents:UIControlEventTouchUpInside];
//    UIBarButtonItem* leftItem = [[UIBarButtonItem alloc] initWithCustomView:left];
//    self.navigationItem.leftBarButtonItem = leftItem;
//    
//}
//-(void)navLeftAction:(id)sender
//{
//    [self.navigationController popToRootViewControllerAnimated:YES];
//}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.navigationItem.title = @"翻小译";
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:144.0/255 green:144.0/255 blue:144.0/255 alpha:1];
    self.navigationController.navigationBar.translucent = NO;
    
    //初始化播放器
    self.player = [[AVAudioPlayer alloc]init];
    _textMuArr = [[NSMutableArray alloc]init];
    //切圆角--将语音承接View
    _ButtonView.layer.cornerRadius = 5;
    _ButtonView.layer.masksToBounds = YES;
    _ButtonView.hidden = YES;
    
//        TranslateModel *translateModel = [[TranslateModel alloc]init];
//        [translateModel setSrcText:@"你好\nhello"];
//        [translateModel setDstText:@"hello"];
//        [translateModel setFromWhere:@"from"];
//        [translateModel setMsgType:@"audio"];
//        [_textMuArr addObject:translateModel];
//    
//        translateModel = [[TranslateModel alloc]init];
//        [translateModel setSrcText:@"hello\n你好"];
//        [translateModel setDstText:@"你好"];
//        [translateModel setFromWhere:@"to"];
//        [translateModel setMsgType:@"audio"];
//        [_textMuArr addObject:translateModel];
    
//    translateModel = [[TranslateModel alloc]init];
//    [translateModel setSrcText:@"nihao\n你好"];
//    [translateModel setDstText:@"你好"];
//    [translateModel setFromWhere:@"to"];
//    [translateModel setMsgType:@"audio"];
//    [_textMuArr addObject:translateModel];

    //实现代理
    _pcmRecorder.delegate = self;
    
    
    [self setUpBottomV];
    [self setUpTable];
    
    //监听键盘是否呼出
//    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(upViews:) name:UIKeyboardWillShowNotification object:nil];
//    
//    //添加手势
//    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
//    [self.view addGestureRecognizer:tap];
   
}

//#pragma mark - 键盘弹出时界面上移及还原
//-(void)upViews:(NSNotification *) notification{
//    
//    //获取键盘的高度
//    NSDictionary *userInfo = [notification userInfo];
//    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGRect keyboardRect = [aValue CGRectValue];
//    int keyBoardHeight = keyboardRect.size.height;
//    
//    //使视图上移
//    CGRect viewFrame = self.view.frame;
//    viewFrame.origin.y = -keyBoardHeight;
//    self.view.frame = viewFrame;
//}



-(void)tapAction{
    
    if ([_replyView isFirstResponder]&&UIKeyboardDidShowNotification)
    {
        
        [_replyView resignFirstResponder];
        
        //使视图还原
        CGRect viewFrame = self.view.frame;
        viewFrame.origin.y = 0;
        self.view.frame = viewFrame;
        
    }
}


//设置底部按钮
-(void)setUpBottomV{
    [_Redkeyboard addTarget:self action:@selector(pinglunplyInputView:) forControlEvents:UIControlEventTouchUpInside];
    [_BluKeyboard addTarget:self action:@selector(bluePinglunplyInputView:) forControlEvents:UIControlEventTouchUpInside];
//
//    [_redTapBtn addTarget:self action:@selector(redTapBtnTap) forControlEvents:UIControlEventTouchUpInside];
//    [_blueTapBtn addTarget:self action:@selector(blueTapBtnTap) forControlEvents:UIControlEventTouchUpInside];
    [_ChangeButton addTarget:self action:@selector(changeButtonTap:) forControlEvents:UIControlEventTouchUpInside];
//
//    //录音
    [_RedVoice addTarget:self action:@selector(RedVoiceTouchDown) forControlEvents:UIControlEventTouchUpInside];
    //录音
    [_BluVoice addTarget:self action:@selector(BlueVoiceTouchDown) forControlEvents:UIControlEventTouchUpInside];

}
//改变语种
-(void)changeButtonTap:(id)sender{
    NSString *tempCodeStr = _fromLancode;
    _fromLancode = _toLancode;
    _toLancode = tempCodeStr;
    
    NSString *tempStr = _RedLanguage.text;
    _RedLanguage.text = _BluLanguage.text;
    _BluLanguage.text = tempStr;
}

//跳转进入选择语言种类页面
- (void)redTapBtnTap
{
    LanguageTBV *languageTableView = [LanguageTBV new];
    languageTableView.redLanguage = _fromLancode;
    languageTableView.fromWhere = @"redTap";
    [self.navigationController pushViewController:languageTableView animated:YES];
    
}
//跳转进入选择语言种类页面
- (void)blueTapBtnTap
{
    LanguageTBV *languageTableView = [LanguageTBV new];
    languageTableView.redLanguage = _toLancode;
    languageTableView.fromWhere = @"blueTap";
    [self.navigationController pushViewController:languageTableView animated:YES];
    
}


//左侧录音
-(void)RedVoiceTouchDown{

    fromWhere =@"from";
    NSLog(@"点击录音");
    [_iflyRecognizerView start];
    
    NSLog(@"左侧录音语言%@",_fromLancode);
    
}

////右侧录音
-(void)BlueVoiceTouchDown{
    
    fromWhere = @"to";
    [_iflyRecognizerView start];
    
}

-(void)initRecognizer
{
    IATConfig *instance = [IATConfig sharedInstance];
    if ([instance.language isEqualToString:[IATConfig chinese]]) {
        //设置语言
        [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
        //设置方言
        [_iflyRecognizerView setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
    }else if ([instance.language isEqualToString:[IATConfig english]]) {
        //设置语言
        [_iflyRecognizerView setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
    }
}
#pragma mark 科大讯飞
- (void)initiFlyReconizerView{
    _iflyRecognizerView = [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
    //    _iflyRecognizerView.hidden = YES;
    _iflyRecognizerView.backgroundColor = [UIColor grayColor];
    _iflyRecognizerView.delegate = self;
    [_iflyRecognizerView setParameter: @"iat" forKey: [IFlySpeechConstant IFLY_DOMAIN]];
    //asr_audio_path保存录音文件名，如不再需要，设置value为nil表示取消，默认目录是documents
    [_iflyRecognizerView setParameter:@"asrview.pcm " forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
    //启动识别服务
    //    [_iflyRecognizerView start];
    
    
    //初始化录音器
    //    if (_pcmRecorder == nil)
    //    {
    //        _pcmRecorder = [IFlyPcmRecorder sharedInstance];
    //    }
    //
    //    _pcmRecorder.delegate = self;
    //
    //    [_pcmRecorder setSample:[IATConfig sharedInstance].sampleRate];
    //
    //    [_pcmRecorder setSaveAudioPath:nil];    //不保存录音文件
    //
    //    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapView)];
    //    tap.cancelsTouchesInView = NO;
    //    [_iflyRecognizerView addGestureRecognizer:tap];
}
/*识别结果返回代理
 @param resultArray 识别结果
 @ param isLast 表示是否最后一次结果
 */
- (void)onResult: (NSArray *)resultArray isLast:(BOOL) isLast
{
    TranslateModel *translateModel = [TranslateModel new];
    translateModel.msgType = @"audio";
    
    NSLog(@"======%@",resultArray);
    NSDictionary *bigDic = resultArray.firstObject;
    NSString *keyStr = bigDic.allKeys.lastObject;
    NSData *data = [keyStr dataUsingEncoding:NSUTF8StringEncoding];
    if (data == nil) {
        return;
    }
    NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
    NSArray *wsArray = [jsonDic objectForKey:@"ws"];
    for (NSDictionary *wsDic in wsArray) {
        NSArray *cwArray = [wsDic objectForKey:@"cw"];
        NSDictionary *cwDic = cwArray.lastObject;
        NSString *string = [cwDic objectForKey:@"w"];
        NSLog(@"----string%@",string);
        if (self.text == nil) {
            self.text = string;
        } else {
            self.text = [self.text stringByAppendingString:string];
        }
        NSLog(@"self.text == %@",self.text);
        //        self.resultLabel.text = self.text;
    }
    NSLog(@"循环外的text == %@",self.text);
    self.str = [NSString stringWithFormat:@"%@",self.text];
    if (self.string == nil || [self.string isEqualToString:@""]) {
        // 请求baidu翻译接口
        [self requestBaiduTranslate:self.str massgaeType:translateModel.msgType];
    }
    self.string = _str;
    
    if (isLast) {
        self.string = @"";
        self.text = @"";
        _str = @"";

    }
    NSLog(@"resultArray == %@",resultArray);

    
}
/*识别会话错误返回代理
 @ param  error 错误码
 */
- (void)onError: (IFlySpeechError *) error
{
    NSLog(@"error == %@",error);
}

-(void)initAudioSession{
    
    NSError *error;
    [[AVAudioSession sharedInstance] setActive:YES error:&error];
    
    // add event handler, for this example, it is `volumeChange:` method
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(volumeChanged) name:@"AVSystemController_SystemVolumeDidChangeNotification" object:nil];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
}

- (void)volumeChafromLanCodenged:(NSNotification *)notification
{
    // service logic here.
    
    NSLog(@"noti");
    
}

//自适应文字宽度
+ (CGFloat)widthForLableText:(NSString*)text ForTextSize:(CGFloat)size
{
    CGRect rect = [text boundingRectWithSize:CGSizeMake(1000,25) options:(NSStringDrawingUsesLineFragmentOrigin) attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:size] } context:nil];
    return rect.size.width;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


//MD5加密
+(NSString *)md5HexDigest:(NSString*)input
{
    const char *cStr = [input UTF8String];
    unsigned char digest[CC_MD5_DIGEST_LENGTH];
    
    CC_MD5(cStr, (CC_LONG)strlen(cStr), digest);
    
    NSMutableString *result = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [result appendFormat:@"%02x", digest[i]];
    }
    
    return result;
}




-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSMutableArray *senderAnimationImages = [[NSMutableArray alloc] initWithObjects: [UIImage imageNamed:SENDER_ANIMATION_IMAGEVIEW_IMAGE_01], [UIImage imageNamed:SENDER_ANIMATION_IMAGEVIEW_IMAGE_02], [UIImage imageNamed:SENDER_ANIMATION_IMAGEVIEW_IMAGE_03], [UIImage imageNamed:SENDER_ANIMATION_IMAGEVIEW_IMAGE_04], nil];
    NSMutableArray *recevierAnimationImages = [[NSMutableArray alloc] initWithObjects: [UIImage imageNamed:RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_01], [UIImage imageNamed:RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_02], [UIImage imageNamed:RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_03], [UIImage imageNamed:RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_04], nil];
    
    TranslateToolCell *cell = [TranslateToolCell cellWithTableView:tableView];
    
    //取消点击效果
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.backgroundColor=[UIColor whiteColor];
    TranslateModel *translateModel = _textMuArr[indexPath.row];
    cell.translateModel = translateModel;
    if ([translateModel.fromWhere isEqualToString:@"from"]) {
        
        if ([translateModel.srcText rangeOfString:@"\n"].location != NSNotFound) {
            //设置翻译的文字为其他颜色
            NSMutableAttributedString *srcTextString = [[NSMutableAttributedString alloc]initWithString:translateModel.srcText];
            NSRange rang = NSMakeRange([translateModel.srcText rangeOfString:@"\n"].location, translateModel.srcText.length - [translateModel.srcText rangeOfString:@"\n"].location);
            [srcTextString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:rang];
            cell.textLb.attributedText = srcTextString;
            
        }
        
        if ([translateModel.msgType isEqualToString:@"audio"]) {
            cell.leftAudioImgV.hidden=NO;
            cell.rightAudioImgV.hidden=YES;
        }else{
            cell.leftAudioImgV.hidden=YES;
            cell.rightAudioImgV.hidden=YES;
        }
        cell.leftAudioImgV.image = [UIImage imageNamed:RECEIVER_ANIMATION_IMAGEVIEW_IMAGE_DEFAULT];
        cell.leftAudioImgV.animationDuration = 1;
        cell.leftAudioImgV.animationImages = recevierAnimationImages;
    }else{
        if ([translateModel.srcText rangeOfString:@"\n"].location != NSNotFound) {
            //设置翻译的文字为其他颜色
            NSMutableAttributedString *srcTextString = [[NSMutableAttributedString alloc]initWithString:translateModel.srcText];
            NSRange rang = NSMakeRange([translateModel.srcText rangeOfString:@"\n"].location, translateModel.srcText.length - [translateModel.srcText rangeOfString:@"\n"].location);
            [srcTextString addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:rang];
            cell.rightTextLb.attributedText = srcTextString;
        }
        if ([translateModel.msgType isEqualToString:@"audio"]) {
            cell.leftAudioImgV.hidden=YES;
            cell.rightAudioImgV.hidden=NO;
        }else{
            cell.leftAudioImgV.hidden=YES;
            cell.rightAudioImgV.hidden=YES;
        }
        cell.rightAudioImgV.image = [UIImage imageNamed:SENDER_ANIMATION_IMAGEVIEW_IMAGE_DEFAULT];
        cell.rightAudioImgV.animationDuration = 1;
        cell.rightAudioImgV.animationImages = senderAnimationImages;
    }
    
    return cell;
}

-(void)startAudioAnimation:(TranslateToolCell*)cell
{
    
    [cell.leftAudioImgV startAnimating];
    [cell.rightAudioImgV startAnimating];
}

-(void)stopAudioAnimation:(TranslateToolCell*)cell
{
    [cell.leftAudioImgV stopAnimating];
    [cell.rightAudioImgV stopAnimating];
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    didSelect = [tableView cellForRowAtIndexPath:indexPath];
    //    indexPathAll = [_xiTongMsgTable indexPathForCell:cell];
    
    TranslateModel *translateModel =_textMuArr[indexPath.row];
    if([translateModel.msgType isEqualToString:@"audio"]){
        
        //初始化对象
        speechPlayer = [[AVSpeechSynthesizer alloc]init];
        speechPlayer.delegate=self;//挂上代理
        utterance = [[AVSpeechUtterance alloc]initWithString:[NSString stringWithFormat:@"%@",translateModel.dstText]];//需要转换的文字
        utterance.rate=0.4;// 设置语速，范围0-1，注意0最慢，1最快；AVSpeechUtteranceMinimumSpeechRate最慢，AVSpeechUtteranceMaximumSpeechRate最快
        
        //utterance.pitchMultiplier = 2;//声调[0 ~ 2];
        //解析可以翻译语音种类
//        NSString *path = [[NSBundle mainBundle]pathForResource:@"audioLanguang" ofType:@"plist"];
//        NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:path];
//        
//        NSArray *langunagArray = dict[@"langunagArray"];
//        NSString *translateLanguageAudio;
//        for (int i = 0; i < langunagArray.count; i++) {
//            if ([[langunagArray[i] substringWithRange:NSMakeRange(0, 2)] isEqualToString:[NSString stringWithFormat:@"%@",[translateModel.toLanuage substringWithRange:NSMakeRange(0, 2)]]]) {
//                translateLanguageAudio = langunagArray[i];
//            }
//        }
//        AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:[NSString stringWithFormat:@"%@",translateLanguageAudio]];//设置发音
        
        
        
        AVSpeechSynthesisVoice *voice = [AVSpeechSynthesisVoice voiceWithLanguage:[NSString stringWithFormat:@"%@",translateModel.toLanuage]];//设置发音

        utterance.voice= voice;
        
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        //默认情况下扬声器播放
        [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
        
        [speechPlayer speakUtterance:utterance];//开始
        //播放动画
        //    [self startTranslateAudioAnimation];
        [self startAudioAnimation:didSelect];
    }
    
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didStartSpeechUtterance:(AVSpeechUtterance*)utterance{
    
    NSLog(@"---开始播放");
    
}
- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didFinishSpeechUtterance:(AVSpeechUtterance*)utterance{
    //    [self stopTranslateAudioAnimation];
    [self stopAudioAnimation:didSelect];
    NSLog(@"---完成播放");
    
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didPauseSpeechUtterance:(AVSpeechUtterance*)utterance{
    
    NSLog(@"---播放中止");
    
    
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didContinueSpeechUtterance:(AVSpeechUtterance*)utterance{
    
    NSLog(@"---恢复播放");
    
}

- (void)speechSynthesizer:(AVSpeechSynthesizer*)synthesizer didCancelSpeechUtterance:(AVSpeechUtterance*)utterance{
    
    NSLog(@"---播放取消");
    
}

//文字
#pragma mark - 输入框
-(void)pinglunplyInputView:(id)sender{
    fromWhere = @"from";
    [self setUpReply];
}

-(void)bluePinglunplyInputView:(id)sender{
    fromWhere = @"to";
    [self setUpReply];
}

-(void)setUpReply{
    _replyView = [[YMReplyInputView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height - 84, self.view.frame.size.width,44) andAboveView:self.view];
    _replyView.delegate = self;
    [self.view addSubview:self.replyView];
}

- (void)YMReplyInputWithReply:(NSString *)replyText appendTag:(NSInteger)inputTag{
    
    [self requestTextTranslate:replyText];
}


- (void)destorySelf{
    
    [self.replyView removeFromSuperview];
    _replyView = nil;
    
}
#pragma mark - table
-(void)setUpTable{
    
    _messageTable.dataSource=self;
    _messageTable.delegate=self;
    _messageTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _textMuArr.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TranslateModel *translateModel = _textMuArr[indexPath.row];
    NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:translateModel.srcText];
    UILabel *alabel=[[UILabel alloc]init];
    alabel.attributedText = attrStr;
    // 计算文本的大小
    CGSize textSize = [alabel.text boundingRectWithSize:CGSizeMake(200, MAXFLOAT) // 用于计算文本绘制时占据的矩形块
    
                                                options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading // 文本绘制时的附加选项
                                             attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:14],NSFontAttributeName, nil]        // 文字的属性
                                                context:nil].size;
    
    
    if([translateModel.msgType isEqualToString:@"audio"]){
        return textSize.height+40+40;
    }
    return textSize.height+40;
    //    return 100;
}


#pragma mark - 生成当前时间字符串
+ (NSString*)GetCurrentTimeString{
    NSDateFormatter *dateformat = [[NSDateFormatter  alloc]init];
    [dateformat setDateFormat:@"yyyyMMddHHmmss"];
    
    return [dateformat stringFromDate:[NSDate date]];
}
//移动到最底部
- (void)scrollViewToBottom:(BOOL)animated
{
    if (_messageTable.contentSize.height > _messageTable.frame.size.height)
    {
        CGPoint offset = CGPointMake(0, _messageTable.contentSize.height - _messageTable.frame.size.height);
        [_messageTable setContentOffset:offset animated:animated];
    }
}
#pragma mark 语音翻译
- (void)requestBaiduTranslate:(NSString*)translateStr massgaeType:(NSString*)msgType
{
    //百度翻译
    NSString *appid = @"20161106000031401";
    NSString *baiduKey = @"eDvSJRb3zwlpzpBEDsKn";
    //http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=2015063000000001&salt=1435660288&sign=f89f9594663708c1605f3d736d01d2d4
    NSString *sign = [NSString stringWithFormat:@"%@%@%@%@",appid,translateStr,@"1435660288",baiduKey];
    NSLog(@"md5加密-%@",[TranslationViewController md5HexDigest:sign]);
    NSString *fromLanStr;
    NSString *toLanStr;
    if([fromWhere isEqualToString:@"from"]){
        fromLanStr = _fromLancode;
        toLanStr = _toLancode;
    }else{
        fromLanStr = _toLancode;
        toLanStr = _fromLancode;
    }
    
    //from -原语言
    //    NSString *CommonInfoUrl = [@"" stringByAppendingFormat:@"http://api.fanyi.baidu.com/api/trans/vip/translate?q=%@&from=%@&to=%@&appid=%@&salt=%@&sign=%@",translateStr,_fromLancode,_toLancode,appid,@"1435660288",[TranslationViewController md5HexDigest:sign]];
    
    //测试
    NSString *CommonInfoUrl = [@"" stringByAppendingFormat:@"http://api.fanyi.baidu.com/api/trans/vip/translate?q=%@&from=%@&to=%@&appid=%@&salt=%@&sign=%@",translateStr,fromLanStr,toLanStr,appid,@"1435660288",[TranslationViewController md5HexDigest:sign]];
    CommonInfoUrl = [CommonInfoUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [HWHttpTool post:CommonInfoUrl params:nil success:^(id json) {
        NSLog(@"翻译请求成功- %@", json );
        NSDictionary *jsonDict = (NSDictionary *)json;
        
        NSArray *translationArray =jsonDict[@"trans_result"];
        NSDictionary *translationDict = [translationArray firstObject];
        NSLog(@"------------>>>%@",translationArray);
        NSLog(@"翻译结果:==========>>>%@",[translationDict valueForKey:@"dst"]);
        TranslateModel *translateModel = [[TranslateModel alloc]init];
        [translateModel setSrcText:[NSString stringWithFormat:@"%@\n%@",translateStr,[translationDict valueForKey:@"dst"]]];
        
        //            [translateModel setFromWhere:fromWhere];
        [translateModel setDstText:[translationDict valueForKey:@"dst"]];//翻译后的文本
        [translateModel setFromLanuage:jsonDict[@"from"]];
        [translateModel setToLanuage:jsonDict[@"to"]];
        [translateModel setMsgType:msgType];
        [translateModel setFromWhere:fromWhere];
        [_textMuArr addObject:translateModel];
        [_messageTable reloadData];
        [self scrollViewToBottom:YES];
        
        NSLog(@"---------->>srcText%@",translateModel.srcText);
        NSLog(@"---------->>fromLanuage%@",translateModel.fromLanuage);
        NSLog(@"---------->>toLanuage%@",translateModel.toLanuage);
        NSLog(@"---------->>dstText%@",translateModel.dstText);
        
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"TranslationList" object:nil];
        
    } failure:^(NSError *error) {
        NSLog(@"翻译请求失败-%@", error);
    }];
    
}

#pragma mark 文字翻译
- (void)requestTextTranslate:(NSString*)translateStr
{
    //百度翻译
    NSString *appid = @"20161106000031401";
    NSString *baiduKey = @"eDvSJRb3zwlpzpBEDsKn";
    
    NSString *sign = [NSString stringWithFormat:@"%@%@%@%@",appid,translateStr,@"1435660288",baiduKey];
    NSLog(@"md5加密-%@",[TranslationViewController md5HexDigest:sign]);
    
    NSString *fromLanStr;
    NSString *toLanStr;
    if([fromWhere isEqualToString:@"from"]){
        fromLanStr = _fromLancode;
        toLanStr = _toLancode;
        
    }else{
        fromLanStr = _toLancode;
        toLanStr = _fromLancode;
    }
    
    //from -原语言
    //    NSString *CommonInfoUrl = [@"" stringByAppendingFormat:@"http://api.fanyi.baidu.com/api/trans/vip/translate?q=%@&from=%@&to=%@&appid=%@&salt=%@&sign=%@",translateStr,_fromLancode,_toLancode,appid,@"1435660288",[TranslationViewController md5HexDigest:sign]];
    
    //测试
    NSString *CommonInfoUrl = [@"" stringByAppendingFormat:@"http://api.fanyi.baidu.com/api/trans/vip/translate?q=%@&from=%@&to=%@&appid=%@&salt=%@&sign=%@",translateStr,fromLanStr,toLanStr,appid,@"1435660288",[TranslationViewController md5HexDigest:sign]];
    NSLog(@"CommonInfoUrl === %@",CommonInfoUrl);
    
    CommonInfoUrl = [CommonInfoUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [HWHttpTool post:CommonInfoUrl params:nil success:^(id json) {
        NSLog(@"翻译请求成功- %@", json );
        NSDictionary *jsonDict = (NSDictionary *)json;
        
        NSArray *translationArray =jsonDict[@"trans_result"];
        NSDictionary *translationDict = [translationArray firstObject];
        NSLog(@"------------>>>%@",translationArray);
        NSLog(@"翻译结果:==========>>>%@",[translationDict valueForKey:@"dst"]);
        TranslateModel *translateModel = [[TranslateModel alloc]init];
        [translateModel setSrcText:[NSString stringWithFormat:@"%@\n%@",translateStr,[translationDict valueForKey:@"dst"]]];
        
        //            [translateModel setFromWhere:fromWhere];
        [translateModel setDstText:jsonDict[@"dst"]];
        [translateModel setFromLanuage:jsonDict[@"from"]];
        [translateModel setToLanuage:jsonDict[@"to"]];
        [translateModel setFromWhere:fromWhere];//来自红方还是蓝方
        
        
        [_textMuArr addObject:translateModel];
        [_messageTable reloadData];
        [self scrollViewToBottom:YES];
        
        NSLog(@"srcText---------->>%@",translateModel.srcText);
        NSLog(@"fromLanuage---------->>%@",translateModel.fromLanuage);
        NSLog(@"toLanuage---------->>%@",translateModel.toLanuage);
        
        
        
    } failure:^(NSError *error) {
        NSLog(@"翻译请求失败-%@", error);
    }];
    
}
@end
